<script setup lang="ts">
// Define props for the component
interface Props {
  id?: string;
  value?: string;
  text?: string;
  selected?: boolean;
  disabled?: boolean;
  freeform?: boolean;
  form?: string;
  name?: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: undefined,
  value: '',
  text: undefined,
  selected: false,
  disabled: false,
  freeform: false,
  form: undefined,
  name: undefined,
});

// Define emits for the component
const emit = defineEmits<{
  (e: 'select', selected: boolean): void;
}>();

// Reference to the native element
const optionRef = ref<HTMLElement | null>(null);

// Watch for changes in the selected state
watch(
  () => props.selected,
  (newValue) => {
    if (!optionRef.value) return;

    // Update the selected state on the native element
    (optionRef.value as any).selected = !!newValue;
  },
  { immediate: true },
);

// Watch for changes in the disabled state
watch(
  () => props.disabled,
  (newValue) => {
    if (!optionRef.value) return;

    // Update the disabled state on the native element
    (optionRef.value as any).disabled = !!newValue;
  },
  { immediate: true },
);

onMounted(() => {
  if (!optionRef.value) return;

  // Add event listener for selected state changes
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.attributeName === 'aria-selected') {
        const selected =
          optionRef.value?.getAttribute('aria-selected') === 'true';
        emit('select', selected);
      }
    });
  });

  observer.observe(optionRef.value, {
    attributes: true,
    attributeFilter: ['aria-selected'],
  });
});
</script>

<template>
  <fluent-option
    ref="optionRef"
    :id="id"
    :value="value"
    :text="text"
    :selected="selected"
    :disabled="disabled"
    :freeform="freeform"
    :form="form"
    :name="name"
  >
    <slot></slot>
    <!-- eslint-disable-next-line vue/no-deprecated-slot-attribute -->
    <slot name="checked-indicator" slot="checked-indicator"></slot>
    <!-- eslint-disable-next-line vue/no-deprecated-slot-attribute -->
    <slot name="description" slot="description"></slot>
    <!-- eslint-disable-next-line vue/no-deprecated-slot-attribute -->
    <slot name="start" slot="start"></slot>
  </fluent-option>
</template>
